import datetime
import json
import os
import pickle
import re
import threading
import time
from concurrent.futures import ThreadPoolExecutor

import schedule

import config
import tool
from functools import reduce

from mail import Mail163
from thread.test import strat_msg


'发送验证码'
def register_exx():

    if not config.run_is:
        return

    path=tool.TOOL.getPropath() + '/cookies_163.obj'

    while 1:
        try:
            if os.path.getsize(path)!=0:
                break
        except FileNotFoundError:
            pass

    f= open(path, 'rb')
    config.cookies_163 = pickle.load(f)
    f.close()

    aList = os.getcwd().split('\\')[:-1]
    path = (reduce(lambda x, y: x + '\\' + y, aList))
    mail_file = [os.path.join(path, name) for name in os.listdir(path) if
                 name.find('_' + os.path.basename(config.path_163)) > -1]

    if len(mail_file) == 0:
        tool.TOOL.create_mail_text()
        register_exx()


    if len(mail_file) < config.thead_max:
        thread_number = len(mail_file)
    else:
        thread_number = config.thead_max

    executor = ThreadPoolExecutor(thread_number)
    print('实际开通线程数为：%d' % thread_number)
    text_num = int(len(mail_file) / thread_number)

    index = 0
    end = text_num
    treaders = []
    for i in range(thread_number):
        result = mail_file[index:end]
        if len(result) == 0:
            break
        index = end
        end = end + text_num
        treaders.append(executor.submit(strat_msg, result))







def job():

    for j in config.list_job:
        code=j[1](j[2],2,j[5])
        if code==None:
            continue
        msg=j[3](j[0],code,j[4])
        print(msg)
        config.list_job.remove(j)
    print('当前还有%d没有验证注册' % len(config.list_job))


def job1():
    path = tool.TOOL.getPropath() +'/suessce.txt'
    while 1:
        try:
            if os.path.getsize(path)!=0:
                break
        except FileNotFoundError:
            pass
    f = open(path, 'r')

    path1=tool.TOOL.getPropath() + '/cookies_163.obj'
    w= open(path1, 'rb')
    config.cookies_163 = pickle.load(w)
    w.close()

    path2 = tool.TOOL.getPropath() + '/youbi.txt'
    y=open(path2,'a+')

    for line in f.readlines():
        try:

            l = line.strip().replace('\n', '')
            if l == '':
                continue
            l = re.split(config.split_title + '+', l)
            msg_mail=config.cookies_163[l[0]]
            m = Mail163('coinsuper', '【业务通知', True)
            m.cookies = msg_mail[0]
            m.mail_163_url = msg_mail[1]
            msg=m.inbox_mail()[1]
            if msg.find('已发完') > -1:
                config.run_is=False
            else:
                y.write(l[0] + '---' + l[1] + '---' + msg + '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n')
        except Exception:
            pass
    y.close()


def job2():
    config.run_is=True
    register_exx()




schedule.every(2).minutes.do(job)
schedule.every(8).minutes.do(job1)
schedule.every().day.at("23:58").do(job2)

def r_start():
    #threading.Thread(target=register_exx).start()
    print('注册定时成功！')
    while True:
        schedule.run_pending()
        time.sleep(1)


if __name__ == '__main__':
    # register_exx()
    #threading.Thread(target=register_exx).start()
    while True:
        schedule.run_pending()
        time.sleep(1)

